package com.shop.autoshop.service.imp;

import com.shop.autoshop.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service("uploadService")
public class UploadServiceImp implements UploadService {
    @Override
    public String uploadImg(MultipartFile file) {
        String type = null;
        String path = null;
        if(file == null){
            return "{\n" +
                    "  \"code\": 0\n" +
                    "  ,\"msg\": \"无文件上传\"\n" +
                    "  ,\"data\": {\n" +
                    "    \"src\": \"\"\n" +
                    "  }\n" +
                    "}  ";
        }
        String fileName = file.getOriginalFilename();
        // 判断文件类型
        type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
        if(type == null){
            return "{\n" +
                    "  \"code\": 0\n" +
                    "  ,\"msg\": \"文件格式错误\"\n" +
                    "  ,\"data\": {\n" +
                    "    \"src\": \"\"\n" +
                    "  }\n" +
                    "}  ";
        }else if(!type.equals("jpg") && !type.equals("png") && !type.equals("gif") && !type.equals("jpeg")){
            return "{\n" +
                    "  \"code\": 0\n" +
                    "  ,\"msg\": \"文件格式错误\"\n" +
                    "  ,\"data\": {\n" +
                    "    \"src\": \"\"\n" +
                    "  }\n" +
                    "}  ";
        }else{
            String realPath = "D:\\webimg\\";
            int randNum = (int)Math.random()*100;
            String newfileName = String.valueOf(System.currentTimeMillis())+String.valueOf(randNum)+"."+type;
            path = realPath+newfileName;
            //System.out.println(path);
            try {
                file.transferTo(new File(path));
                return "{\n" +
                        "  \"code\": 1\n" +
                        "  ,\"msg\": \"上传成功\"\n" +
                        "  ,\"data\": {\n" +
                        "    \"src\": \"/uploads/"+newfileName+"\"\n" +
                        "  }\n" +
                        "}  ";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "{\n" +
                "  \"code\": 0\n" +
                "  ,\"msg\": \"未知错误\"\n" +
                "  ,\"data\": {\n" +
                "    \"src\": \"\"\n" +
                "  }\n" +
                "}  ";
    }
}
